<template>
  <Modal
    :open="open"
    :title="$t('daprplus.auth.user.setPasswordTitle', { name: user.nickName })"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Form
      :model="passwordForm"
      :rules="passwordRules"
      ref="passwordFormRef"
      layout="vertical"
    >
      <Form.Item name="password" :label="$t('daprplus.auth.user.password')">
        <Input.Password v-model:value="passwordForm.password" />
      </Form.Item>
      <Form.Item
        name="confirmPassword"
        :label="$t('daprplus.auth.user.confirmPassword')"
      >
        <Input.Password v-model:value="passwordForm.confirmPassword" />
      </Form.Item>
    </Form>
  </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Input, message } from 'ant-design-vue';
import { ref, reactive, defineProps, defineEmits } from 'vue';
import { $t } from '@vben/locales';
import type { UserOutDto } from './user.vue';
import { setPasswordApi } from '#/api/daprplus';

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  user: {
    type: Object as () => UserOutDto,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:open', 'success']);

const confirmLoading = ref(false);
const passwordFormRef = ref();
const passwordForm = reactive({
  password: '',
  confirmPassword: '',
});

// 处理取消按钮点击
function handleCancel() {
  emit('update:open', false);
}

// 密码验证规则
const passwordRules = {
  password: [
    { required: true, message: $t('daprplus.auth.user.passwordRequired') },
    { min: 6, max: 20, message: $t('daprplus.auth.user.passwordLength') },
  ],
  confirmPassword: [
    {
      required: true,
      message: $t('daprplus.auth.user.confirmPasswordRequired'),
    },
    {
      validator: (_rule: any, value: string) => {
        if (value !== passwordForm.password) {
          return Promise.reject($t('daprplus.auth.user.passwordMismatch'));
        }
        return Promise.resolve();
      },
    },
  ],
};

// 处理密码提交
async function handleSubmit() {
  if (!props.user || !props.user.id) return;

  try {
    await passwordFormRef.value.validate();
    confirmLoading.value = true;

    // 调用设置密码API
    await setPasswordApi({
      userId: props.user.id,
      password: passwordForm.password,
      confirmPassword: passwordForm.confirmPassword,
    });

    message.success($t('daprplus.auth.user.passwordSetSuccess'));
    emit('update:open', false);
    emit('success');
  } catch (error) {
    console.error('密码设置失败:', error);
    message.error($t('daprplus.auth.user.passwordSetFailed'));
  } finally {
    confirmLoading.value = false;
  }
}
</script>

<style scoped></style>
